package wadassignment2

import java.util.Date;

class Bid {

	private static final Float BID_INC = 0.5f;

	Float amount;
	Date dateCreated;

	static belongsTo = [bidder:Customer, listing:Listing]

	
	static constraints = {
		amount(nullable: false, validator : {val, obj ->
			if( val < obj.listing.startingBid )
				return false
			else if(obj.listing.bids == null )
				return true

			int size = obj.listing.bids.size()

			if (size < 2)
				return true
			else {
				Bid aBid = (Bid)obj.listing.bids[0]
				def max = aBid.amount

				def currentBid = (Bid)obj.listing.bids[size-1]
				def currentAmount = currentBid.amount
				for(int i = 0; i < obj.listing.bids.size(); i++ ) {
					Bid oldBid = (Bid)obj.listing.bids[i]
					def oldAmount = oldBid.amount
					if(oldBid.amount != currentAmount && oldAmount > max)
						max = oldAmount
				}

				if(currentAmount >= max + BID_INC)
					return true
				else
					return false
			}
		})
	} 
}
